package com.travel.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import com.travel.core.AbstractDao.Direction;
import com.travel.core.DaoFactory;
import com.travel.dao.IRestaurantDao;
import com.travel.entities.Restaurant;
import com.travel.util.Constants;

public class TopHotRestaurantsServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private static final Logger LOGGER = LogManager.getLogger(TopHotRestaurantsServlet.class);

    private static final IRestaurantDao RESTAURANT_DAO = DaoFactory.getDao(IRestaurantDao.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String type = request.getParameter("type");
        String orderBy;
        if ("0".equals(type)) {
            orderBy = "shopTaste";
        } else if ("1".equals(type)) {
            orderBy = "shopEnvironment";
        } else {
            orderBy = "shopService";
        }
        List<Restaurant> restaurants = RESTAURANT_DAO.selectList(orderBy, Direction.DESC, 0, 10);
        JSONArray jsonArray = new JSONArray();
        for (Restaurant u : restaurants) {
            JSONObject json = new JSONObject();
            try {
                json.put("shopName", u.getShopName());
                json.put("shopUrl", u.getShopUrl());
                json.put("shopAddress", u.getShopAddress());
                json.put("shopTell", u.getShopTell());
                json.put("shopOpenTime", u.getShopOpenTime());
                json.put("shopPersonAve", u.getShopPersonAve());
                json.put("shopTaste", u.getShopTaste());
                json.put("shopEnvironment", u.getShopEnvironment());
                json.put("shopService", u.getShopService());
                json.put("shopStar", u.getShopStar());
            } catch (Exception e) {
                LOGGER.error(e.getLocalizedMessage(), e);
            }
            jsonArray.put(json);
        }
        response.setCharacterEncoding(Constants.UTF_8);
        response.getWriter().append(jsonArray.toString());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
